<?php

namespace app\common\model;

use think\Model;
use think\Session;

class GoodsModel extends Model
{
    protected $auto = ['content'];
    protected $pk = 'id';
    protected $table = 'basic_goods';
    protected $autoWriteTimestamp = true;

    protected static function init()
    {
        GoodsModel::beforeInsert(function ($GoodsModel) {
            isset($GoodsModel->shop_price)&&$GoodsModel->shop_price = yuanToFen($GoodsModel->shop_price);
            isset($GoodsModel->market_price)&&$GoodsModel->market_price = yuanToFen($GoodsModel->market_price);
        });
    }

    //获取商品列表
    public function getGoodsList($params)
    {
        $curPage = isset($params['page'])&&$params['page']>=1  ? $params['page']: 1;
        $pageSize = 12;
        $where['status'] = ['neq', 111];
        if (!empty($params)) {
            checkString($params['goods_name']) && $where['goods_name'] = ['like', $params['goods_name']];
            isset($params['status'])&&$params['status']!=-1&&$where['status'] = ['=', $params['status']];
            
        }

        $totalRow = self::where($where)->count();
        $data = self::where($where)->order("id desc")->page($curPage, $pageSize)->select();
        $data = empty($data) ? [] : collection($data)->toArray();
        // var_dump(  $list );die();

        Session::set($this->table."_where", $where);
        
        return [
            'pageSize' => $pageSize,
            'totalRow' => $totalRow,
            'curPage' => $curPage,
            'data' => $data
        ];
    }

    //获取单个商品
    public function getGoodsById($goodsId)
    {
        $goods = self::find($goodsId);
        $goodsImage = (new GoodsImagesModel)->where(['goods_id' => $goodsId, 'status' => 1])->select();
        $goodsImage = empty($goodsImage) ? [] : collection($goodsImage)->toArray();

        return [
            'goods' => $goods,
            'goodsImage' => $goodsImage,
        ];
    }

    //删除
    public function deleteAll($id)
    {
        if (!is_array($id)) {
            $id = [$id];
        }

        return self::where("id", "in", $id)->update([
            'status' => 111,
            'update_time' => time()
        ]);
    }

    //批量改变状态
    public function changeStatus($ids, $status)
    {
        return self::where("id", "in", $ids)->update([
            'status' => $status,
            'update_time' => time()
        ]);
    }

    protected function setContentAttr($value)
    {
        return $value == null ? '' : $value;
    }
}
